import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/pages/login/privacy_page.dart';
import 'package:chathouse/pages/login/sms_check_page.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:chathouse/widgets/form_widgets/form_widgets.dart';
import 'package:chathouse/widgets/my_drop_down_widget.dart';
import 'package:chathouse/widgets/my_input_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:get/get.dart';
import '../../constant/app_constant.dart';
import '../../model/response_bean.dart';
import '../../net/Apis.dart';
import '../../public/Obj.dart';
import '../../util/font_utils.dart';
import '../../util/toast_util.dart';

//註冊
class RegisterPage extends StatefulWidget {
  RegisterPage({Key? key}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  String areaSelectedValue = "0";
  List<MyDropDownBean> areas = [
    MyDropDownBean("0", "+852"),
    MyDropDownBean("1", "+86"),
  ];

  TextEditingController nameTextEditingController = TextEditingController();
  TextEditingController phoneTextEditingController = TextEditingController();
  TextEditingController emailTextEditingController = TextEditingController();
  TextEditingController pwdTextEditingController = TextEditingController();
  TextEditingController surePwdTextEditingController = TextEditingController();

  TextEditingController referencePhoneTextEditingController =
      TextEditingController();

  bool canRegister = false;
  bool agree = false;

  @override
  void initState() {
    super.initState();
    nameTextEditingController.addListener(() {
      setCanClick();
    });
    phoneTextEditingController.addListener(() {
      setCanClick();
    });
    emailTextEditingController.addListener(() {
      setCanClick();
    });
    pwdTextEditingController.addListener(() {
      setCanClick();
    });
    surePwdTextEditingController.addListener(() {
      setCanClick();
    });
  }

  @override
  void dispose() {
    super.dispose();
    nameTextEditingController.dispose();
    phoneTextEditingController.dispose();
    emailTextEditingController.dispose();
    pwdTextEditingController.dispose();
    surePwdTextEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(),
      body: ListView(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "註冊",
                textAlign: TextAlign.left,
                style: getTextStyle(32.sp,
                    fontType: FontType.MID, color: Colors.black),
              ).setContainer(
                  width: double.infinity, margin: EdgeInsets.only(top: 4.w)),
              MyInputWidget(
                title: "稱呼",
                controller: nameTextEditingController,
              ).setContainer(margin: EdgeInsets.only(top: 26.w)),
              Text(
                "電話號碼",
                style: getTextStyle(18.sp,
                    color: Colors.black, fontType: FontType.DEFAULT),
              ).setContainer(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 14.w, bottom: 4.w)),
              Row(
                children: [
                  MyDropDownWidget(areaSelectedValue, areas, (val) {
                    areaSelectedValue = val;
                  }).setContainer(width: 100.w),
                  Expanded(
                      child: MyInputWidget(
                    placeholder: "電話號碼",
                    controller: phoneTextEditingController,
                  ).setContainer(margin: EdgeInsets.only(left: 6.w)))
                ],
              ),
              Text(
                "電郵*",
                style: getTextStyle(18.sp,
                    color: Colors.black, fontType: FontType.DEFAULT),
              ).setContainer(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 14.w, bottom: 4.w)),
              MyInputWidget(
                leftIcon: Icon(
                  Icons.email_outlined,
                  size: 24.w,
                  color: MyColors.gary_155155155,
                ).setContainer(margin: EdgeInsets.only(right: 4.w)),
                controller: emailTextEditingController,
              ),
              MyInputWidget(
                title: "密碼",
                placeholder: "",
                obscureText: true,
                controller: pwdTextEditingController,
                isShoweYe: true,
              ).setContainer(margin: EdgeInsets.only(top: 14.w)),
              MyInputWidget(
                title: "確認密碼",
                placeholder: "",
                obscureText: true,
                isShoweYe: true,
                controller: surePwdTextEditingController,
              ).setContainer(margin: EdgeInsets.only(top: 14.w)),
              Text(
                "推薦人電話號碼",
                style: getTextStyle(18.sp,
                    color: Colors.black, fontType: FontType.DEFAULT),
              ).setContainer(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 14.w, bottom: 4.w)),
              Row(
                children: [
                  MyDropDownWidget(areaSelectedValue, areas, (val) {
                    areaSelectedValue = val;
                  }).setContainer(width: 100.w),
                  Expanded(
                      child: MyInputWidget(
                    placeholder: "推薦人電話號碼",
                    controller: referencePhoneTextEditingController,
                  ).setContainer(margin: EdgeInsets.only(left: 6.w)))
                ],
              ),
              Row(children: [
                Checkbox(
                    value: agree,
                    onChanged: (val) {
                      setState(() {
                        agree = !agree;
                      });
                      setCanClick();
                    }).setContainer(width: 22.w, height: 22.w),
                Text("閱覽", style: getTextStyle(16.sp, color: Colors.black)),
                Text(" 平台使用條款",
                        style:
                            getTextStyle(16.sp, color: MyColors.blue_49127167))
                    .setOnClickListener(() {
                  toPrivacyPage(0);
                }),
                Text(
                  " 及 ",
                  style: getTextStyle(16.sp, color: Colors.black),
                ),
                Text("私隱政策",
                        style:
                            getTextStyle(16.sp, color: MyColors.green_69157154))
                    .setOnClickListener(() {
                  toPrivacyPage(1);
                }),
              ]).setContainer(margin: EdgeInsets.only(top: 36.w)),
              FormWidgets.getTextButton("立即註冊", MyColors.green_69157154,
                      enable: canRegister)
                  .setContainer(
                      margin:
                          EdgeInsets.only(left: 44.w, right: 44.w, top: 30.w))
                  .setOnClickListener(() {
                registerAction();
              }),
            ],
          ).setContainer(padding: EdgeInsets.symmetric(horizontal: 28.w))
        ],
      ).setContainer(color: Colors.white),
    );
  }

  void toPrivacyPage(int index) async {
    bool? result = await Get.to(PrivacyPage(
      initialIndex: index,
    ));
    if (result != null && result == true) {
      setState(() {
        agree = true;
        setCanClick();
      });
    }
  }

  void setCanClick() {
    setState(() {
      canRegister = nameTextEditingController.text.isNotEmpty &&
          phoneTextEditingController.text.isNotEmpty &&
          pwdTextEditingController.text.isNotEmpty &&
          surePwdTextEditingController.text.isNotEmpty &&
          agree && emailTextEditingController.text.isNotEmpty;
    });
  }

  void registerAction() {
    if (!canRegister) return;
    if (emailTextEditingController.text.isNotEmpty &&
        !emailTextEditingController.text.contains("@")) {
      ToastUtil.showToast("請輸入正確電郵格式");
      return;
    }
    if (emailTextEditingController.text.isNotEmpty &&
        !emailTextEditingController.text.contains("@")) {
      ToastUtil.showToast("請輸入正確電郵格式");
      return;
    }
    if (pwdTextEditingController.text != surePwdTextEditingController.text) {
      ToastUtil.showToast("兩次輸入密碼不一致");
      return;
    }
    String area = areas
        .firstWhere((element) {
          return areaSelectedValue == element.value;
        })
        .name
        .substring(1);
    //查重
    var params = {
      "membersName": nameTextEditingController.text,
      "memberPassword": pwdTextEditingController.text,
      "rawPassword": surePwdTextEditingController.text,
      "membersIdentity": AppConstant.userRole == UserRole.c ? "1" : "2"
    };
    if (phoneTextEditingController.text.isNotEmpty) {
      params["membersPhone"] = (area + phoneTextEditingController.text);
    }
    if (emailTextEditingController.text.isNotEmpty) {
      params["membersEmail"] = emailTextEditingController.text;
    }
    FocusManager.instance.primaryFocus?.unfocus();
    ResponseBean result;
    Obj.showLoading();
    Apis.duplicateChecking(params)
        .then((response) => {
              Obj.dismissLoading(),
              result = ResponseBean.fromJson(response?.data ?? {}),
              if (result.isRequestSuccess)
                {
                  Get.to(SmsCheckPage(
                      nameTextEditingController.text,
                      phoneTextEditingController.text,
                      emailTextEditingController.text,
                      pwdTextEditingController.text,
                      area,
                      referencePhoneTextEditingController.text)),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }
}
